package com.yunmai.library.util;

import android.content.Context;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

/**
 * 像素单位转换工具类
 *
 * @author littleGnAl
 *         Created on 16/4/14.
 */
public class DensityUtils {

    /**
     * dp转px
     *
     * @param dp dp值
     * @return dp转成px的值
     */
    public static int dp2px(Context context, float dp) {
        try {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (dp * scale + 0.5f);
        } catch (Exception ee) {
            ee.printStackTrace();
        }
        return 0;
    }

    /**
     * dp转px
     *
     * @param dp dp值
     * @return dp转成px的值
     */
    public static float dp2pxfloat(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (dp * scale + 0.5f);
    }

    /**
     * px转dp
     *
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    /**
     * sp转px
     *
     * @param spValue sp值
     * @return sp转成px的值
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale =
            context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * px转sp
     *
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

    public static Point getScreenSize(Context context) {
        Point outPoint = new Point();

        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay()
            .getSize(outPoint);

        return outPoint;
    }


    public static int getScreenWidth(Context mContext) {
        if (mContext == null) {
            return 0;
        }
        // 方法1 Android获得屏幕的宽和高
        WindowManager windowManager =
            (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        display.getMetrics(displayMetrics);
        return displayMetrics.widthPixels; //得到宽度
    }

}
